package top.sqdpt.third.strategy;

import top.sqdpt.third.config.WeatherProperties;
import top.sqdpt.third.config.WeatherProperties.WeatherConfig;
import top.sqdpt.third.entity.dto.WeatherRequestDTO;
import top.sqdpt.third.utils.LoadBalancerUtil;

import java.util.List;

/**
 * 天气策略抽象基类
 * 统一处理配置注入逻辑
 */
public abstract class AbstractWeatherStrategy implements WeatherStrategy {

    protected final List<WeatherConfig> configs;

    protected AbstractWeatherStrategy(WeatherProperties properties) {
        //判空
        if (properties == null) {
            throw new IllegalArgumentException("properties不能为空");
        }
        //判空
        if (properties.getConfigs() == null || properties.getConfigs().isEmpty()) {
            throw new IllegalArgumentException("properties.getConfigs()不能为空");
        }
        //根据getWeatherType()负载均衡获取配置      
        List<WeatherConfig> configs = properties.getConfigs().stream()
                .filter(c -> c.getType() == getWeatherType())
                .toList();
        if (configs.isEmpty()) {
            throw new IllegalStateException(getWeatherType() + "天气配置不存在");
        }
        this.configs = configs;
    }

    protected WeatherConfig getConfig() {
        return LoadBalancerUtil.random(configs);
    }

    protected String buildForecastUrl(WeatherRequestDTO requestDTO) {
        return getConfig().getForecastUrl();
    }

    protected String buildForecastUrl() {
        return buildForecastUrl(null);
    }

    protected String buildNowUrl(WeatherRequestDTO requestDTO) {
        return getConfig().getNowUrl();
    }

    protected String buildNowUrl() {
        return buildNowUrl(null);
    }

} 